﻿using Business.Solr;
using OpenPop.Mime.Header;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace Business {
    public class NewMessageFilter {
        private readonly string[] _FromAddressRules;
        private readonly Regex _SubjectRegex;
        private readonly SolrClient _SolrClient;
        
        public NewMessageFilter(string from, string subjectRegex, SolrClient solrClient) {
            _FromAddressRules = ParseRules(from);
            _SubjectRegex = new Regex(subjectRegex, RegexOptions.IgnoreCase);
            _SolrClient = solrClient;
        }

        private string[] ParseRules(string ruleExpression) {
            var rules = Regex.Split(ruleExpression, @";|,|\s+");
            return rules;
        }

        private bool IsEmptyRule(string[] rules) {
            return rules == null || rules.Length == 0 || rules.All(_ => string.IsNullOrWhiteSpace(_));
        }

        public bool IsNewResume(MessageHeader header) {
            return IsResumeEmail(header) && IsNotExistsMessage(header.MessageId);
        }

        /// <summary>
        /// 是否为简历邮件
        /// </summary>
        /// <param name="header"></param>
        /// <returns></returns>
        private bool IsResumeEmail(MessageHeader header) {
            return (IsEmptyRule(_FromAddressRules) || _FromAddressRules.Any(rule => IsMatch(header.From.Address, rule)))
                && _SubjectRegex.IsMatch(header.Subject);
        }

        /// <summary>
        /// 邮件地址是否匹配规则
        /// </summary>
        /// <param name="address"></param>
        /// <param name="addressRule"></param>
        /// <returns></returns>
        private bool IsMatch(string address, string addressRule) {
            if (addressRule.StartsWith("*"))
                return address.EndsWith(addressRule.Substring(1), StringComparison.CurrentCultureIgnoreCase);
            return string.Compare(address, addressRule, true) == 0;
        }

        private bool IsNotExistsMessage(string messageId) {
            return true;
            var repo = new ResumeRepo(_SolrClient);
            return repo.IsNotExistsMessage(messageId);
        }
    }
}
